package com.example.sunmiv1.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.SkuInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AddGoodsSkuAdapterTest extends BaseAdapter {

    private Context context;
    private List<SkuInfo> list;
    private ViewHolder viewHolder;
    private List<String> skuClass = new ArrayList<>();//規格分類名稱
    private List<SkuInfo.DataBean.ListBean> skuList = new ArrayList<>();
    private static final String TAG = "AddGoodsSkuAdapter";
    private int classIndex = 0;
    private Operation operation;
    private LayoutInflater mInflater;
    private ArrayAdapter arrayAdapter;


    private Paint mSearchHistoryPaint;
    private int mPaddingSize;
    private SearchHistoryAdapter mSearchHistoryAdapter;


    public AddGoodsSkuAdapterTest(Context context, List<SkuInfo> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = View.inflate(context, R.layout.add_goods_sku_adapter_test, null);
        viewHolder = new ViewHolder(convertView);
        final int index = position;
        skuClass.clear();
        for (int i = 0; i < list.get(index).getData().size(); i++) {
            skuClass.add(list.get(index).getData().get(i).getName());
        }
        final Spinner spinner = viewHolder.skuAdapterSpinner;
        final RecyclerView tagFlowLayout = viewHolder.skuAdapterFlow;
        arrayAdapter = new ArrayAdapter(context, R.layout.item_select, skuClass);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        spinner.setAdapter(arrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (classIndex != position && classIndex != list.get(index).getData().size()) {
                    for (int i = 0; i < list.get(index).getData().get(classIndex).getList().size(); i++) {
                        list.get(index).getData().get(classIndex).getList().get(i).setChecked(false);
                    }
                }
                list.get(index).setDataIndex("" + position);
                classIndex = position;
                skuList.clear();
                for (int i = 0; i < list.get(index).getData().get(classIndex).getList().size(); i++) {
                    skuList.add(list.get(index).getData().get(classIndex).getList().get(i));
                    Log.e(TAG, "onItemSelected: name2=" + list.get(index).getData().get(classIndex).getList().get(i).getName() +
                            list.get(index).getData().get(classIndex).getList().get(i).isChecked());
                }
                /*TagAdapter<List<SkuInfo.DataBean.ListBean>> tagAdapter1 = new TagAdapter(skuList) {
                    @Override
                    public View getView(FlowLayout parent, int position, Object o) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.tv_shop, tagFlowLayout, false);
                        tv.setText(((SkuInfo.DataBean.ListBean) o).getName());
                        if (((SkuInfo.DataBean.ListBean) o).isChecked()) {
                            tv.setTextColor(context.getResources().getColor(R.color.login_textColor1));
                        }
                        return tv;
                    }
                };
                tagFlowLayout.setAdapter(tagAdapter1);*/

                mSearchHistoryAdapter = new SearchHistoryAdapter(skuList, context);
                tagFlowLayout.setAdapter(mSearchHistoryAdapter);
                Log.e(TAG, "onItemSelected: 切換分類1");
                operation.refreshHeight();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        if (!TextUtils.isEmpty(list.get(index).getDataIndex())) {
//            spinner.setOnItemSelectedListener(null);
            spinner.setSelection(Integer.parseInt(list.get(index).getDataIndex()));
        }
        mInflater = LayoutInflater.from(context);
        /*TagAdapter<List<SkuInfo.DataBean.ListBean>> tagAdapter = new TagAdapter(skuList) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {
                TextView tv = (TextView) mInflater.inflate(R.layout.tv_shop, viewHolder.skuAdapterFlow, false);
                tv.setText(((SkuInfo.DataBean.ListBean) o).getName());
                if (((SkuInfo.DataBean.ListBean) o).isChecked()) {
                    tv.setTextColor(context.getResources().getColor(R.color.login_textColor1));
                }
                return tv;
            }
        };
        tagFlowLayout.setAdapter(tagAdapter);
        tagFlowLayout.setOnTagClickListener((view, positions, parent1) -> {
            list.get(index).getData().get(classIndex).getList().get(positions).setChecked(
                    !list.get(index).getData().get(classIndex).getList().get(positions).isChecked()
            );
            for (int i = 0; i < list.get(index).getData().get(classIndex).getList().size(); i++) {
                Log.e(TAG, "onItemSelected: name4=" + list.get(index).getData().get(classIndex).getList().get(i).getName() +
                        list.get(index).getData().get(classIndex).getList().get(i).isChecked());
            }
            return true;
        });*/
        final TextView delete = viewHolder.skuAdapterDelete;
        delete.setOnClickListener(v -> operation.delete(index));
        final TextView classAdd = viewHolder.skuAdapterClassAdd;
        final EditText classAddEdit = viewHolder.skuAdapterClassEdit;
        classAdd.setOnClickListener(v -> {
            boolean flag = false;
            int class1 = 0;
            if (!TextUtils.isEmpty(classAddEdit.getText().toString().trim())) {
                for (int i = 0; i < list.get(index).getData().size(); i++) {
                    if (classAddEdit.getText().toString().trim().equals(list.get(index).getData().get(i).getName())) {
                        class1 = i;
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                spinner.setSelection(class1);
                arrayAdapter.notifyDataSetChanged();
                Log.e(TAG, "getView: 點擊");
                operation.refreshHeight();
            } else {
                operation.addClass(index, classAddEdit.getText().toString().trim());
            }
        });
        final TextView skuAdd = viewHolder.skuAdapterSkuAdd;
        final EditText skuAddEdit = viewHolder.skuAdapterSkuEdit;
        skuAdd.setOnClickListener(v -> {
            boolean flag = false;
            if (!TextUtils.isEmpty(skuAddEdit.getText().toString().trim())) {
                for (int i = 0; i < list.get(index).getData().get(classIndex).getList().size(); i++) {
                    if (skuAddEdit.getText().toString().trim().equals(list.get(index).getData().get(classIndex).getList().get(i).getName())) {
                        flag = true;
                        list.get(index).getData().get(classIndex).getList().get(i).setChecked(true);
                    }
                }
            }
            if (flag) {
                skuAddEdit.setText("");
                /*TagAdapter<List<SkuInfo.DataBean.ListBean>> tagAdapter1 = new TagAdapter(skuList) {
                    @Override
                    public View getView(FlowLayout parent, int position, Object o) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.tv_shop, viewHolder.skuAdapterFlow, false);
                        tv.setText(((SkuInfo.DataBean.ListBean) o).getName());
                        if (((SkuInfo.DataBean.ListBean) o).isChecked()) {
                            tv.setTextColor(context.getResources().getColor(R.color.login_textColor1));
                        }
                        return tv;
                    }
                };
                tagFlowLayout.setAdapter(tagAdapter1);*/
            } else {
                operation.addSku(index, classIndex, list.get(index).getData().get(classIndex).getId(), skuAddEdit.getText().toString().trim());
            }
        });


        tagFlowLayout.setHasFixedSize(true);
        mSearchHistoryPaint = new Paint();//畫筆用來計算文字的寬度
        //設置文字的大小，注意佈局文件裏寫的是sp，這裏需要進行轉換成對應的px，我這裏就不寫了
        mSearchHistoryPaint.setTextSize(40);
        //textview的大小，包括文字大小和左右內邊距，所以這個值表示內邊距大小，同樣注意轉換
        mPaddingSize = 0;
        //獲取屏幕的寬度，我這裏rccyclerview正好是屏幕的寬度，否則應替換爲rec的寬度
        final int width = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth()-80;
        //這裏講網格的數量設置爲屏幕的寬度，網格無限小
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, width);
        //設置每個文字佔據的網格數
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                for (int i = 0; i < skuList.size(); i++) {
                    //就是這裏 需要測量文字的寬度，加上左右內邊距
                    int textWidth = (int) mSearchHistoryPaint.measureText(skuList.get(position).getName()) + mPaddingSize;
                    //如果文字的寬度超過屏幕的寬度，那麼我們就設置爲屏幕寬度
                    return textWidth > width ? width : textWidth;
                }
                return 0;
            }
        });
        tagFlowLayout.setLayoutManager(gridLayoutManager);
        mSearchHistoryAdapter = new SearchHistoryAdapter(skuList, context);
        tagFlowLayout.setAdapter(mSearchHistoryAdapter);

        return convertView;
    }

    class SearchHistoryAdapter extends RecyclerView.Adapter<AddGoodsSkuAdapterTest.RecyclerViewHolder> {

        private List<SkuInfo.DataBean.ListBean> listBeans;
        private Context context;

        public SearchHistoryAdapter(List<SkuInfo.DataBean.ListBean> listBeans, Context context) {
            this.listBeans = listBeans;
            this.context = context;
        }

        @Override
        public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tv_shop, parent, false);
            return new AddGoodsSkuAdapterTest.RecyclerViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerViewHolder holder, int position) {
            holder.tvShopTv.setText(listBeans.get(position).getName());
            if (listBeans.get(position).isChecked()) {
                holder.tvShopTv.setTextColor(context.getResources().getColor(R.color.login_textColor1));
            } else {
                holder.tvShopTv.setTextColor(context.getResources().getColor(R.color.text_333));
            }
        }


        @Override
        public int getItemCount() {
            return listBeans == null ? 0 : listBeans.size();
        }
    }

    static class RecyclerViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_shop_tv)
        TextView tvShopTv;

        public RecyclerViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface Operation {
        void delete(int position);

        void addClass(int position, String className);

        void addSku(int position, int classIndex, String id, String skuName);

        void refreshHeight();
    }

    public void Click(Operation operation) {
        this.operation = operation;
    }

    static class ViewHolder {
        @BindView(R.id.skuAdapter_spinner)
        Spinner skuAdapterSpinner;
        @BindView(R.id.skuAdapter_classEdit)
        EditText skuAdapterClassEdit;
        @BindView(R.id.skuAdapter_classAdd)
        TextView skuAdapterClassAdd;
        @BindView(R.id.skuAdapter_skuEdit)
        EditText skuAdapterSkuEdit;
        @BindView(R.id.skuAdapter_skuAdd)
        TextView skuAdapterSkuAdd;
        @BindView(R.id.skuAdapter_flow)
        RecyclerView skuAdapterFlow;
        @BindView(R.id.skuAdapter_delete)
        TextView skuAdapterDelete;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
